package payment

import (
	"cloud_android_backend/api/common"
	"cloud_android_backend/pkg/middleware/authorization"
	model "cloud_android_backend/pkg/models/users"
	"cloud_android_backend/pkg/modules/orders"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/golang/glog"
	rb "modules.tenxcloud.com/common/middleware"
	"net/http"
)

func Register(application *gin.RouterGroup) {
	application.POST("/payment/pay", rb.RequestBody, authorization.TokenCheck, Payment)
}

type PaymentParam struct {
	OrderId int64 `json:"order_id"`
}

func Payment(c *gin.Context) {
	li, exists := c.Get(authorization.LoginUserKey)
	if !exists {
		c.AbortWithStatusJSON(common.ErrorResponse("get user from content failed"))
		return
	}
	current := li.(*model.User)
	var paymentForm PaymentParam
	//print(current)
	body, _ := c.Get(rb.RequestBodyKey)
	if err := json.Unmarshal(body.([]byte), &paymentForm); err != nil {
		glog.Error(err)
		c.AbortWithStatusJSON(common.ErrorResponse(err.Error()))
		return
	}
	orderInfo, err := orders.GetOrderById(paymentForm.OrderId)
	if err != nil {
		glog.Error(err)
		c.AbortWithStatusJSON(common.ErrorResponse(err.Error()))
		return
	}
	if orderInfo.UserId != current.UserID {
		c.AbortWithStatusJSON(common.ErrorResponse("you have no permission to pay this order"))
		return
	}
	payResult, err := orders.Payment(paymentForm.OrderId)
	if err != nil {
		glog.Error(err)
		c.AbortWithStatusJSON(common.ErrorResponse(err.Error()))
		return
	}
	c.JSON(http.StatusOK, common.SuccessResponse(payResult))
}
